package com.test.tinyurl.domain.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.tinyurl.domain.bean.Link;
import com.test.tinyurl.domain.mapper.LinkMapper;
import com.test.tinyurl.domain.service.LinkService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 短链服务层
 */
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {

    @Override
    public String insertLink(String fullLink, String hashCode) throws Exception {

        //生成5位数字符串
        String shortLink = RandomStringUtils.randomAlphanumeric(5);

        //生成link对象
        Link link = new Link();
        link.setFullLink(fullLink);
        link.setShortLink(shortLink);
        link.setHashCode(hashCode);
        super.save(link);

        return shortLink;
    }

    @Override
    public boolean selectLink(String hashCode) throws Exception {
        List<Link> linkList = super.list(Wrappers.<Link>lambdaQuery().eq(Link::getHashCode, hashCode));
        return CollectionUtils.isNotEmpty(linkList);
    }
}
